<?php

class order_calendarModel extends Model
{   

    //顺延日期
    function switchDate($dateArr,$uid){
        if(!is_array($dateArr)){
            return false;
        }
        foreach($dateArr as $date){
            if(!$date)continue;
            $date = date("Y-m-d",strtotime($date));
            $last_date = $this->where(array('uid'=>$uid))->order("date desc")->find();
            if($last_date){
                $week = date("N",strtotime($last_date['date']));
                if(in_array($week,array(5,6,7))){
                    $add_time = 86400 * (8-$week);
                    $next_date = date("Y-m-d",strtotime($last_date['date'])+$add_time);
                }else{
                    $next_date = date("Y-m-d",strtotime($last_date['date']) + 86400);
                }
            }
            $this->where(array('date'=>$date,'uid'=>$uid))->save(array('status'=>-2));
            
            $data = $this->field('uid,address,linkname,mobile,order_id,orderId')->where(array('date'=>$date,'uid'=>$uid))->find();
            $data['date'] = $next_date;
            $data['created'] = time();
            $this->data($data)->add();
            
        }
        return true;
    }

    //取消日期
    function cancelDate($dateArr,$uid){
        if(!is_array($dateArr)){
            return false;
        }

        $coupon = array(
            'uid'=>$uid,
            'title'=>"35元代金券",
            'expire_at' =>date("Y-m-d",time() + 365*24*3600),
            'created_at'=>time(),
            'price'=>35
            );

        foreach($dateArr as $date){
            if(!$date)continue;
            $date = date("Y-m-d",strtotime($date));
            $calendar = $this->where(array('date'=>$date,'uid'=>$uid))->find();
            $order = M('item_order')->where(array('id'=>$calendar['order_id']))->find();
            $coupon['price'] = round($order['order_sumPrice']/$order['days']);
            $coupon['title'] = $coupon['price']."元代金券";
            $coupon['order_id'] = $calendar['order_id'];
            $this->where(array('date'=>$date,'uid'=>$uid))->save(array('status'=>-1));
            M('coupon')->data($coupon)->add();
        }
        return true;

    }

    //根据ID取消/顺延日期
    function changeDateByIds($idArr,$act){
        if(!is_array($idArr)){
            return false;
        }

        foreach ($idArr as $id) {
            if(!$id)continue;
            $item = $this->find($id);
            if($item){
                $dateArr = array($item['date']);
                if($act == 'cancel'){
                    $this->cancelDate($dateArr,$item['uid']);
                }else if($act == 'switch'){
                    $this->switchDate($dateArr,$item['uid']);
                }
            }
        }
    }
}